<template>
  <div class="app-container app-container-compactness">

    <upload-excel-component style="margin-bottom: 12px;" :on-success="handleSuccess" :before-upload="beforeUpload" />
    <div>
      <el-button type="danger" :disabled="!multipleSelection.length" @click="uploadData">选中上传</el-button>
      <el-button style="margin-left: 0" type="warning" :disabled="!multipleSelection.length" @click="deleteChecked">删除选中</el-button>
      <!--      <el-button @click="validAllEvent">整个表格校验</el-button>-->
      <!--      <el-button @click="fullValidEvent">校验</el-button>-->
    </div>

    <ux-grid
      ref="plxTable"
      size="mini"
      border
      show-summary
      :show-overflow="'title'"
      :show-header-overflow="'title'"
      keep-source
      stripe
      :rules="rules"
      height="500"
      :edit-config="{trigger: 'click', mode: 'cell'}"
      @selection-change="handleSelectionChange"
    >
      <ux-table-column type="checkbox" width="60" />
      <ux-table-column type="index" title="行号" width="80" />

      <ux-table-column field="project_client" title="项目和委托方*" edit-render>
        <template v-slot:edit="scope">
          <el-cascader
            v-model="scope.row.project_client"
            :options="selectData"
            style="width: 100%"
          />
        </template>
        <template v-slot="{ row }">{{ project_client_label(row) }}</template>
      </ux-table-column>

      <ux-table-column prop="goods_number" :edit-render="{autofocus: '.el-input__inner'}" field="goods_number" title="商品总数量*">
        <template v-slot:edit="scope">
          <el-input v-model="scope.row.goods_number" />
        </template>
        <template v-slot="{ row }">{{ row.goods_number }}</template>
      </ux-table-column>

      <ux-table-column prop="customer_business_number" :edit-render="{autofocus: '.el-input__inner'}" field="customer_business_number" title="客户业务单号*">
        <template v-slot:edit="scope">
          <el-input v-model="scope.row.customer_business_number" />
        </template>
        <template v-slot="{ row }">{{ row.customer_business_number }}</template>
      </ux-table-column>

      <ux-table-column prop="waybill" :edit-render="{autofocus: '.el-input__inner'}" field="waybill" title="运单号*">
        <template v-slot:edit="scope">
          <el-input v-model="scope.row.customer_businwaybilless_number" />
        </template>
        <template v-slot="{ row }">{{ row.waybill }}</template>
      </ux-table-column>

      <ux-table-column field="transport_type" title="运输方式" :edit-render="{autofocus: '.el-input__inner'}">
        <template v-slot:edit="scope">
          <el-select v-model="scope.row.transport_type" @change="$refs.plxTable.updateStatus(scope)">
            <el-option label="陆运" value="陆运" />
            <el-option label="海运" value="海运" />
            <el-option label="空运" value="空运" />
          </el-select>
        </template>
        <template v-slot="{ row }">{{ row.transport_type }}</template>
      </ux-table-column>

      <ux-table-column prop="clause" :edit-render="{autofocus: '.el-input__inner'}" field="clause" title="条款*">
        <template v-slot:edit="scope">
          <el-input v-model="scope.row.clause" />
        </template>
        <template v-slot="{ row }">{{ row.clause }}</template>
      </ux-table-column>

      <ux-table-column prop="new_tray_num" :edit-render="{autofocus: '.el-input__inner'}" field="new_tray_num" title="货物托盘数量*">
        <template v-slot:edit="scope">
          <el-input v-model="scope.row.new_tray_num" />
        </template>
        <template v-slot="{ row }">{{ row.new_tray_num }}</template>
      </ux-table-column>

      <ux-table-column prop="new_goods_dimension" :edit-render="{autofocus: '.el-input__inner'}" field="new_goods_dimension" title="货物尺寸*">
        <template v-slot:edit="scope">
          <el-input v-model="scope.row.new_goods_dimension" />
        </template>
        <template v-slot="{ row }">{{ row.new_goods_dimension }}</template>
      </ux-table-column>

      <ux-table-column prop="new_goods_price" :edit-render="{autofocus: '.el-input__inner'}" field="new_goods_price" title="货物金额*">
        <template v-slot:edit="scope">
          <el-input v-model="scope.row.new_goods_price" />
        </template>
        <template v-slot="{ row }">{{ row.new_goods_price }}</template>
      </ux-table-column>

      <ux-table-column field="shipper_serial_number" title="送货方" :edit-render="{autofocus: '.el-input__inner'}">
        <template v-slot:edit="scope">
          <el-select v-model="scope.row.shipper_serial_number" @change="change_shipper(scope.row,scope)">
            <el-option
              v-for="item in clientList"
              :key="item.serial_number"
              :label="`${item.serial_number}（${item.account_key}）`"
              :value="item.serial_number"
            >
              <span style="float: left">{{ item.serial_number }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.account_key }}</span>
            </el-option>
          </el-select>
        </template>
        <template v-slot="{ row }">{{ shipper_label( row) }}</template>
      </ux-table-column>

      <ux-table-column field="shipper_serial_number" title="收货方" :edit-render="{autofocus: '.el-input__inner'}">
        <template v-slot:edit="scope">
          <el-select v-model="scope.row.consignee_serial_number" @change="change_consignee(scope.row,scope)">
            <el-option
              v-for="item in clientList"
              :key="item.serial_number"
              :label="`${item.serial_number}（${item.account_key}）`"
              :value="item.serial_number"
            >
              <span style="float: left">{{ item.serial_number }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.account_key }}</span>
            </el-option>
          </el-select>
        </template>
        <template v-slot="{ row }">{{ consignee_label( row) }}</template>
      </ux-table-column>

      <!--      <ux-table-column-->
      <!--        title="操作"-->
      <!--        width="200"-->
      <!--        fixed="right"-->
      <!--      >-->
      <!--        <template v-slot="{ row }">-->
      <!--          &lt;!&ndash;判断行是否激活了, 编辑按钮执行的方式就是为了去激活&ndash;&gt;-->
      <!--          <template v-if="$refs.plxTable.isActiveByRow(row)">-->
      <!--            <el-button type="primary" @click="saveEvent(row)">保存</el-button>-->
      <!--            <el-button @click="cancelRowEvent(row)">取消</el-button>-->
      <!--          </template>-->
      <!--          <template v-else>-->
      <!--            <el-button @click="editRowEvent(row)">编辑</el-button>-->
      <!--          </template>-->
      <!--        </template>-->
      <!--      </ux-table-column>-->
    </ux-grid>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { getProject } from '@/api/storehouse'
import { providerList } from '@/api/basics'
import { att } from '@/api/stock'
export default {
  name: 'ImportXlsx',
  components: { UploadExcelComponent },
  data() {
    const projectClientRules = ({ cellValue, rule }) => {
      if (!Array.isArray(cellValue) || cellValue.length != 2) {
        return new Error('请选择项目和委托方')
      }
    }
    return {
      clientParams: {
        page: 1,
        limit: 9999,
        account_code: undefined,
        account_name: undefined
      },
      clientList: [],
      selectList: [],
      multipleSelection: [],
      selectData: [],
      tableKeyMap: {
        '项目和委托方*': 'project_client',
        '运输方式*': 'transport_type',
        '商品总数量*': 'goods_number',
        '运单号*': 'waybill',
        '送货方*': 'shipper_serial_number',
        '收货方*': 'consignee_serial_number',
        '条款*': 'clause',
        '客户业务单号*': 'customer_business_number',
        '货物托盘数量*': 'new_tray_num',
        '货物尺寸*': 'new_goods_dimension',
        '货物金额*': 'new_goods_price'
      },
      rules: {
        project_client: [
          { required: true, validator: projectClientRules, message: '请选择项目和委托方' }
        ],
        goods_number: [
          { required: true, message: '商品总数量不能为空' }
        ]
      },
      tableHeader: [],
      tableData: [],
      columns: []
    }
  },
  computed: {

  },
  created() {
    this.project()
  },
  mounted() {
    this.getClientList()
  },
  methods: {
    // 选择收货方
    change_consignee(row, scope) {
      this.$refs.plxTable.updateStatus(scope)
      this.clientList.forEach(item => {
        if (item.serial_number == row.consignee_serial_number) {
          row.consignee_relation_phone = item.relation_phone
          row.consignee_relation_name = item.relation_name
        }
      })
    },
    // 选择送货方
    change_shipper(row, scope) {
      this.$refs.plxTable.updateStatus(scope)
      this.clientList.forEach(item => {
        if (item.serial_number == row.shipper_serial_number) {
          row.shipper_relation_phone = item.relation_phone
          row.shipper_relation_name = item.relation_name
        }
      })
    },
    getClientList() {
      providerList(this.clientParams).then(response => {
        if (response.code === 10000) {
          this.clientList = response.data
        }
      })
      att().then((response) => {
        if (response.code === 10000) {
          this.selectList = JSON.parse(JSON.stringify(response.data))
        }
      })
    },
    deleteChecked() {
      this.$refs.plxTable.removeCheckboxRow()
      this.multipleSelection = []
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    uploadData() {
      // console.log(this.multipleSelection)
      this.$refs.plxTable.validate(this.multipleSelection).then(data => {
        if (data) { // 失败
          let masStr = ''
          Object.values(data).forEach(errList => {
            errList.forEach(params => {
              const { rowIndex, column, rules } = params
              rules.forEach(rule => {
                masStr += `<p>第 ${rowIndex + 1} 行 ：${rule.message}</p>`
              })
            })
          })
          // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
          return this.$notify.error({
            title: '错误',
            dangerouslyUseHTMLString: true,
            message: masStr,
            duration: 3500
          })
        }

        // 成功往下走
        return this.$message({
          message: '恭喜你，这是一条成功消息',
          type: 'success'
        })
      })
    },
    // 校验
    fullValidEvent() {
      // fullValidate完整校验，和 validate 的区别就是会给每一行进行校验
      this.$refs.plxTable.fullValidate().then(data => {
        // data就是当前检验不通过的
        if (data) {
          let masStr = ''
          Object.values(data).forEach(errList => {
            console.log(errList)
            errList.forEach(params => {
              const { rowIndex, column, rules } = params
              rules.forEach(rule => {
                masStr += `<p>第 ${rowIndex} 行 ${column.title} 校验错误：${rule.message}</p>`
              })
            })
          })
          // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
          this.$notify.error({
            title: '错误',
            dangerouslyUseHTMLString: true,
            message: masStr,
            duration: 1500
          })
        } else {
          // 我用的提示是element-ui的，不要说你没安装element，就说为啥报错
          this.$message({
            message: '校验成功',
            type: 'success',
            duration: 1500
          })
        }
      })
    },
    // 整个表格校验
    validAllEvent() {
      // 1. validate方法 如果你传入一个true， 那么就代表整个表格校验！
      // 2.快速校验，如果存在校验不通过的行，则返回不再继续校验
      this.$refs.plxTable.validate(true).then(data => {
        if (data) {
          this.$message({
            message: '校验不通过',
            type: 'error',
            duration: '1000'
          })
        } else {
          this.$message({
            message: '校验成功',
            type: 'success',
            duration: '1000'
          })
        }
      })
    },
    editRowEvent(row) {
      this.$refs.plxTable.setActiveRow(row)
    },
    consignee_label(row) {
      let label = ''
      this.clientList.forEach(item => {
        if (item.serial_number == row.consignee_serial_number) {
          label = item.account_name
        }
      })
      return label
    },
    shipper_label(row) {
      let label = ''
      this.clientList.forEach(item => {
        if (item.serial_number == row.shipper_serial_number) {
          label = item.account_name
        }
      })
      return label
    },
    project_client_label(row) {
      let label = ''
      this.selectData.forEach(item => {
        if (Array.isArray(row.project_client) && item.value == row.project_client[0]) {
          item.children.forEach(itm => {
            if (itm.value == row.project_client[1]) {
              label = item.label + '/' + itm.label
              return
            }
          })
        }
      })
      return label
    },
    project() {
      const that = this
      getProject().then(response => {
        if (response.code === 10000) {
          that.selectData = response.data
        }
      })
    },
    // 点击保存
    saveEvent(row) {
      // 判断是否发生改变
      console.log(this.$refs.plxTable.isUpdateByRow(row))
      if (this.$refs.plxTable.isUpdateByRow(row)) {
        // 局部保存，并将行数据恢复到初始状态（如果 第二个参数record 为空则不改动行数据，只恢复状态）
        // 必须执行这个，不然下次点击保存，还是保存成功哦！状态没改变哦
        this.$refs.plxTable.reloadRow(row, null, null)
        // ...保存逻辑相关（后端呀，或者前端呀）
        this.$message({
          message: '恭喜你，保存成功',
          type: 'success'
        })
      } else {
        this.$message({
          message: '保存失败，你没改变当前行的数据',
          type: 'error'
        })
      }
    },
    // 转换男女
    getLabel(val) {
      const item = this.sexList.filter(item => item['value'] === val)[0]
      return item ? item.label : ''
    },
    // 转换地址
    getCascader(value, list) {
      const values = value || []
      const labels = []
      const cascaderData = function(index, list) {
        const val = values[index]
        if (list && values.length > index) {
          list.forEach(item => {
            if (item.value === val) {
              labels.push(item.label)
              cascaderData(++index, item.children)
            }
          })
        }
      }
      cascaderData(0, list)
      return labels.join(' / ')
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.multipleSelection = []
      this.tableData = results
      const that = this

      const newData = this.tableData.map(item => {
        console.log(item)
        const newItem = {}
        for (const key in item) {
          if (Object.prototype.hasOwnProperty.call(that.tableKeyMap, key)) {
            newItem[that.tableKeyMap[key] || key] = item[key]
          }
        }
        return newItem
      })
      this.tableData = newData

      this.tableData.forEach(item => {
        // 项目和委托方
        if (item.project_client) {
          const project_client_arr = item.project_client.split('/')
          if (project_client_arr.length == 2) {
            this.selectData.forEach(itm => {
              if (project_client_arr[0] == itm.label) {
                itm.children.forEach(itm1 => {
                  if (itm1.label == project_client_arr[1]) {
                    item.project_client = [itm.value, itm1.value]
                  }
                })
              }
            })
          }
        }

        // 送货方
        this.clientList.forEach(itm => {
          if (itm.serial_number == item.shipper_serial_number) {
            item.shipper_relation_name = itm.account_name
            item.shipper_relation_phone = itm.relation_phone
          }
        })
        // 收货方
        this.clientList.forEach(itm => {
          if (itm.serial_number == item.consignee_serial_number) {
            item.consignee_relation_name = itm.account_name
            item.consignee_relation_phone = itm.relation_phone
          }
        })
      })

      console.log(this.tableData)

      this.tableHeader = header
      this.$refs.plxTable.reloadData(this.tableData)
    }
  }
}
</script>
